package top.yuhaitao.core.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class SimpleZookeeperClient {
    private static final String connectString = "192.168.2.3:2181,192.168.2.4:2181,192.168.2.5:2181";
    private static final Integer sessionTimeout = 2000;
    ZooKeeper zooKeeper = null;


    @Before
    public void zooKeeper() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, watchedEvent -> {
            // 收到时间之后的回调函数
            System.out.println(watchedEvent.getType() + "---" + watchedEvent.getPath());
            // 这里的监听执行到这里就结束了，需要重新注册一个，就会一直循环下去。
            try {
                zooKeeper.getChildren("/", true);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        /**
         * 数据的增删改查
         *
         * ZooDefs.Ids.CREATOR_ALL_ACL 默认的权限
         */
        String zNode = zooKeeper.create("/idea", "idea test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(zNode);
    }

    @Test
    public void getChildren() throws KeeperException, InterruptedException {

        List<String> children = zooKeeper.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }

//        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 判断是否存在节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testExist() throws KeeperException, InterruptedException {
        Stat exists = zooKeeper.exists("/app1", false);
        System.out.println(exists == null ? "not exist" : "exist");
    }

    /**
     * 获取节点数据
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/app1", true, new Stat());
        String s = new String(data, StandardCharsets.UTF_8);
        System.out.println(s);
    }

    /**
     * 删除节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDeleteZnode() throws KeeperException, InterruptedException {
        /**
         * 参数2 删除指定版本
         * 参数-1 删除所有的版本
         */
        zooKeeper.delete("/idea", -1);

    }

    /**
     * 修改节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testSetZnode() throws KeeperException, InterruptedException {

        Stat stat = zooKeeper.setData("/app1", "i miss you".getBytes(), -1);
        System.out.println(stat == null ? "not exist" : "exist");

    }


}
